<?php

namespace app\admin\controller\ykjp\sell;

use app\common\controller\Backend;
use think\Db;

/**
 * 销售出库单
 *
 * @icon fa fa-circle-o
 */
class Delivery extends Backend {

    /**
     * Storage模型对象
     * @var \app\admin\model\ykjp\purchase\Storage
     */
    protected $model = null;
    protected $searchFields = "name";
    protected $distinguish = true;
    protected $wherename = "";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\sell\Delivery;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add() {
        $date = date("Y-m-d", time());
        $this->assign("date", $date);
        if ($this->request->isAjax()) {
            $obj = $this->request->param("obj");
            //获取对应销售单
            if ($obj == 3) {
                $supid = $this->request->param("supid");
                $this->model = new \app\admin\model\ykjp\sell\Sell;
                $this->searchFields = "code";
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->where("customer_info_id", $supid)
                        ->where("status_list", 5)
                        ->order($sort, $order)
                        ->count();
                $list = $this->model
                        ->where("customer_info_id", $supid)
                        ->where($where)
                        ->where("status_list", 5)
                        ->order($sort, $order)
                        ->select();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }
            //获取对应销售单的录单
            if ($obj == 4) {
                $pucId = $this->request->param("ids");
                $order = new \app\admin\model\ykjp\sell\Sell;
                $data = $order->where("firmid", $this->auth->firmid)->where("id", $pucId)->find();
                if ($data) {
                    $model = new \app\admin\model\ykjp\sell\Product;
                    $list = $model->with(['products'])->where("sell_id", $pucId)->where("product.firmid", $this->auth->firmid)->select();
                    // var_dump($list);exit;
                    $row = '';
                    $result = array("product" => $list, "code" => $data, "row" => $row);
                    $this->success(null, null, $result);
                }
                $this->error(__('No Results were found'));
            }
            //添加 销售出库单
            if ($obj == 5) {
                $row = $this->request->param("row/a"); //获取出库单总表数据
                $pdct = $this->request->param("product/a"); //获取出库单副表数据

                $firmid = $this->auth->firmid; //企业ID
                $admin = $this->auth->id; //当前登陆用户ID
                //数据验证
                $purchase = "";
                $pdct[0] = isset($pdct[0]) ? $pdct[0] : "";
                if ($pdct[0] == "") {
                    $this->error(__('Please add item'));
                }
                // 数据格式转换
                $all = json_decode($pdct[0]);
                $tep = $this->model->object_array($all);

                //判断库存是否充足
                for ($i = 0; $i < count($tep); $i++) {
                    //获取当前库存
                    $wp_inventory = Db::name('ykjp_wp_relationship')->where('id', $tep[$i]['wp_id'])->field('inventory')->find();
                    //判断库存
                    if ($wp_inventory['inventory'] < $tep[$i]['nums']) {
                        $this->error('提交失败，库存不足！');
                    }
                }

                //处理要提交的数据
                $current_time = time(); //当前时间
                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
                $row['createtime'] = $current_time; //创建时间
                $row['updatetime'] = $current_time; //更新时间
                $row['billing_time'] = strtotime($row['billing_time']); //制单时间
                $row['delivery_time'] = strtotime($row['delivery_time']); //交货时间
                $row['admin_id'] = $admin;  //制单人员ID
                $row['status_list'] = '1'; //审核状态
                //提交数据（插入销售出库单主表->插入副表并更新关联的wp表（循环修改））
                // 启动事务
                Db::startTrans();
                try {

                    //插入销售出库单主表
                    Db::name('ykjp_delivery')->insert($row);
                    $delivery_id = Db::name('ykjp_delivery')->getLastInsID(); //获取刚插入数据的ID
                    //插入副表并更新关联的wp表
                    for ($i = 0; $i < count($tep); $i++) {

                        $tep[$i]['delivery_id'] = $delivery_id; //设置delivery_id
                        $tep[$i]['createtime'] = $current_time; //设置创建时间
                        $tep[$i]['updatetime'] = $current_time; //设置更新时间

                        Db::name('ykjp_delivery_product')->insert($tep[$i]); //插入副表
                        //更新关联表
                        Db::name('ykjp_wp_relationship')
                                ->where('id', $tep[$i]['wp_id'])
                                ->where('firmid', $this->auth->firmid)
                                ->update([
                                    'inventory' => Db::raw('inventory-' . $tep[$i]['nums']),
                                    'freeze' => Db::raw('freeze+' . $tep[$i]['nums']),
                                    'updatetime' => time(),
                        ]);
                    }

                    // 提交事务
                    Db::commit();
                    $this->success("提交成功", null, array("result" => "success", "url" => url("ykjp/sell/delivery/index")));
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error('提交失败');
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error('提交失败');
                }
                $this->error('提交失败');
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null) {

        if ($this->request->isAjax()) {
            $product = $this->request->param("product/a");
            $row = $this->request->param("row/a");

            $ids = $row['ids'];  //退货单ID
            if ($ids == null) {
                $this->error(__('fail'));
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
            $row['billing_time'] = strtotime($row['billing_time']);  //制单日期
            $row['delivery_time'] = strtotime($row['delivery_time']);  //
            $row['updatetime'] = time();  //更新时间
            //更新销售出库单主表
            $dataRow = $this->model
                    ->where("id", $ids)
                    ->update([
                'linkman' => $row['linkman'],
                'phone' => $row['phone'],
                'billing_time' => $row['billing_time'],
                'delivery_time' => $row['delivery_time'],
                'type' => $row['type'],
                'city' => $row['city'],
                'address' => $row['address'],
                'remark' => $row['remark'],
                'updatetime' => time(),
                'code' => $row['code']
            ]);

            if (!$product) {
                $this->error(__('Product cannot be empty'));
            }
            $product = json_decode($product[0]);
            $product = $this->model->object_array($product);

            //销售副表

            foreach ($product as $key => $val) {
                $id = $val['pro_id'];
                unset($val["pro_id"]);
                $val['updatetime'] = time();
                if ($id) {
                    $up = Db::name('ykjp_delivery_product')->where("id", $id)->where('firmid', $this->auth->firmid)->update($val);
                    if (!$up) {
                        $this->error(null, null, ['result' => "更新出错"]);
                    }
                }
            }


            $this->success(null, null, ['result' => "success"]);
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $detail = $this->model
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->where("id", $ids)
                ->where("status_list", 1)
                ->select();

        $dModel = new \app\admin\model\ykjp\sell\deliveryPro;
        $strProduct = $dModel->with(['products'])->where("delivery_id", $ids)->where('products.firmid', $this->auth->firmid)->select();
        foreach ($strProduct as $key => $val) {
            $pro = json_decode($val['products']['prop']);
            $val['products']['prop'] = $this->model->object_array($pro);

            //根据wp_id查询出库位置
            $wp_id = $strProduct[$key]['wp_id'];
            $arr = Db::name('ykjp_wp_relationship')->where('id', $wp_id)->where('firmid', $this->auth->firmid)->field('warehouse_id,partition_id')->find();

            //获取仓库名称
            $w_name = Db::name('ykjp_warehouse')->where('id', $arr['warehouse_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['w_name'] = $w_name['name'];

            //获取库区名称
            $p_name = Db::name('ykjp_partition')->where('id', $arr['partition_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['p_name'] = $p_name['name'];
        }

        $this->assign("detail", $detail);
        $this->assign("product", $strProduct);
        $date = date("Y-m-d", time());
        $this->assign("date", $date);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail() {
        $ids = $this->request->param("ids");
        if ($ids == "") {
            $this->error("fail", "ykjp/sell/delivery/index");
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = Db::name('ykjp_delivery')
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->where("id", $ids)
                ->select();
        // halt($list);
        $dModel = new \app\admin\model\ykjp\sell\deliveryPro;
        $strProduct = $dModel->with(['products'])->where("delivery_id", $ids)->where('products.firmid', $this->auth->firmid)->select();
        foreach ($strProduct as $key => $val) {
            $pro = json_decode($val['products']['prop']);
            $val['products']['prop'] = $this->model->object_array($pro);

            //根据wp_id查询出库位置
            $wp_id = $strProduct[$key]['wp_id'];
            $arr = Db::name('ykjp_wp_relationship')->where('id', $wp_id)->where('firmid', $this->auth->firmid)->field('warehouse_id,partition_id')->find();

            //获取仓库名称
            $w_name = Db::name('ykjp_warehouse')->where('id', $arr['warehouse_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['w_name'] = $w_name['name'];

            //获取库区名称
            $p_name = Db::name('ykjp_partition')->where('id', $arr['partition_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['p_name'] = $p_name['name'];
        }
        // halt($strProduct);

        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 保存
     */
    public function updateData($ids = null) {
        if ($ids == "") {
            $this->error("fail", "ykjp/purchase/storage/index");
        }
        $row = $this->request->param("row/a");
        $product = $this->request->param("product/a");
        if (!$row || $product == "") {
            $this->error("fail");
        }
        $product = json_decode($product[0]);
        $product = $this->model->object_array($product);
        $firmid = $this->auth->firmid;
        $row['updatetime'] = time();
        $row['delivery_time'] = strtotime($row['delivery_time']);
        $row['billing_time'] = strtotime($row['billing_time']);
        $result = $this->model->where("id", $ids)->where("firmid", $firmid)->update($row);
        $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
        if (!$result) {
            $this->error("update fail");
        }
        $where = [];
        foreach ($product as $key => $val) {
            $id = $val['data_id'];
            unset($val['data_id']);
            $purchase_proid = $val['purchase_proid'];
            unset($val['purchase_proid']);
            $val['updatetime'] = time();
            if ($id) {
                //禁止修改
                $updateData = $stpModel->where("id", $id)->update($val);
                if ($updateData) {
                    $where[] = $id;
                }
            } else {
                $val['storage_id'] = $ids;
                $val['createtime'] = time();
                $val['firmid'] = $firmid;
                $isner = $stpModel->insertGetId($val);
                if ($isner) {
                    $where[] = $isner;
                }
            }
        }
        if ($where) {
            $deletTime = array("deletetime" => time());
            $update = $stpModel->where("storage_id", $ids)->where("id", "not in", $where)->update($deletTime);
        }
        $this->success("update success", null, array("result" => "success"));
    }

    /**
     * 删除
     */
    public function del($ids = null) {
        if ($ids) {
            $firmid = $this->auth->firmid;
            $list = $this->model->where("firmid", $firmid)->where("status", "neq", 3)->where("id", "in", $ids)->select();
            $model = new \app\admin\model\ykjp\purchase\Stoproduct;
            $purchaseModel = new \app\admin\model\ykjp\purchase\Order; //采购单
            $purProModel = new \app\admin\model\ykjp\purchase\Product; //采购产品单
            $count = 0;
            foreach ($list as $key => $val) {
                $id = $val['id'];
                $totalNums = 0;
                $purchase_id = $val['purchase_id'];
                $data = array("deletetime" => time());
                $status = $val['status'];
                //删除恢复库存

                $del = $this->model->where("id", $id)->update($data);
                if ($del) {
                    if ($status != 2) {
                        if ($purchase_id != "" & $purchase_id > 0) {
                            $strPorduct = $model->where("storage_id", $id)->select();
                            $prurche = $purchaseModel->where("id", $purchase_id)->find();
                            $totalNums = 0;
                            foreach ($strPorduct as $key => $pro) {
                                $id = $pro['purchase_proid'];
                                $pruduct = $purProModel->where("id", $id)->find();
                                if ($pruduct) {
                                    $nums = $pruduct['wait_nums'] + $pro['nums'];
                                    $totalNums += $pro['nums'];
                                    $purProModel->where("id", $id)->update(array("wait_nums" => $nums));
                                }
                            }
                            if ($totalNums > 0) {
                                $purchaseModel->where("id", $purchase_id)->update(array("wait_nums" => $totalNums));
                            }
                        }
                        $update = $model->where("storage_id", $id)->where("deletetime", null)->update($data);
                    }
                }
                $count += $del;
            }
            if ($count) {
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 入库
     */
    public function inventory($ids = null) {
        if ($ids) {
            $firmid = $this->auth->firmid;
            $list = $this->model->where("firmid", $firmid)->where("status", "eq", 1)->where("id", "in", $ids)->select();
            if ($list) {
                $model = new \app\admin\model\ykjp\purchase\Stoproduct; //入库产品单
                $modelWp = new \app\admin\model\ykjp\inventory\Wp; //库存
                $modelSta = new \app\admin\model\ykjp\inventory\Statement; //库存流水
                $purProModel = new \app\admin\model\ykjp\purchase\Product; //采购产品单
                $purchaseModel = new \app\admin\model\ykjp\purchase\Order; //采购单
                $productModel = new \app\admin\model\ykjp\product\Product; //商品表
                $resultCount = 0;
                foreach ($list as $key => $val) {
                    $id = $val['id'];
                    $count = 0;
                    $purchase_id = $val['purchase_id'];
                    $stoProduct = $model->where("firmid", $firmid)->where("storage_id", $id)->where("status", "1")->select();
                    $totalnums = 0;
                    foreach ($stoProduct as $key => $pro) {
                        $upStrPodu = $model->where("id", $pro['id'])->update(array('status' => 3, "updatetime" => time()));
                        $count += $upStrPodu;
                        if ($upStrPodu) {
                            $warehouse_id = $pro['warehouse_id'];
                            $partition_id = $pro['partition_id'];
                            $product_id = $pro['product_id'];
                            $where = array(
                                "warehouse_id" => $warehouse_id,
                                "partition_id" => $partition_id,
                                "product_id" => $product_id,
                                "firmid" => $firmid,
                            );
                            $isExist = $modelWp->where($where)->find();
                            if ($isExist) {
                                $nums = $isExist['inventory'] + $pro["nums"];
                                $data = array(
                                    "inventory" => $nums,
                                    "updatetime" => time(),
                                );
                                //更新已有库存
                                $result = $modelWp->where($where)->update($data);
                            } else {
                                $inserData = array(
                                    "warehouse_id" => $warehouse_id,
                                    "partition_id" => $partition_id,
                                    "product_id" => $product_id,
                                    "firmid" => $firmid,
                                    "inventory" => $pro['nums'],
                                    "updatetime" => time(),
                                );
                                //插入新库存
                                $result = $modelWp->insert($inserData);
                            }

                            if ($result) {
                                $sle = $productModel->where("id", $pro['product_id'])->where("firmid", $firmid)->find();
                                if ($sle) {
                                    $inNums = $sle['inventory'] + $pro['nums'];
                                    $productModel->where("id", $pro['product_id'])->where("firmid", $firmid)->update(array("inventory" => $inNums));
                                }
                                $sra = Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->where("id", $warehouse_id)->find();
                                if ($sra) {
                                    $sra = $sra['inventory'] + $pro['nums'];
                                    $sra = Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->where("id", $warehouse_id)->update(array("inventory" => $sra));
                                }
                                $par = Db::name('ykjp_partition')->where("firmid", $this->auth->firmid)->where("id", $partition_id)->find();
                                if ($par) {
                                    $parnums = $par['inventory'] + $pro['nums'];
                                    $par = Db::name('ykjp_partition')->where("firmid", $this->auth->firmid)->where("id", $partition_id)->update(array("inventory" => $parnums));
                                }

                                //库存流水
                                $staData = array(
                                    "firmid" => $firmid,
                                    "product_id" => $product_id,
                                    "warehouse_id" => $warehouse_id,
                                    "partition_id" => $partition_id,
                                    "number" => $pro['nums'],
                                    "type" => "采购入库",
                                    "updatetime" => time(),
                                );
                                $modelSta->insert($staData);

                                //修改入库产品状态
                                // var_dump($pro['id']);
                                // $count+=$model->where("id",$pro['id'])->update(array("status"=>3,"updatetime"=>time()));
                                // var_dump($count);
                                //读取采购单原来对应产品的采购总数
                                if ($pro['purchase_proid'] != "" && $pro['purchase_proid'] > 0) {
                                    $purPorduct = $purProModel->where("firmid", $firmid)->where("id", $pro['purchase_proid'])->find();
                                    if ($purPorduct) {
                                        if ($purPorduct['nums'] == $pro['nums']) {
                                            $totalnums += $pro["nums"];
                                            $purProModel->where("id", $pro['purchase_proid'])->update(array("status" => "3", "updatetime" => time()));
                                        } else {
                                            $proCount = $model->where("status", "3")->where("purchase_proid", $pro['purchase_proid'])->where("firmid", $firmid)->sum("nums");
                                            $totalnums += $proCount;
                                            if ($proCount == $purPorduct['nums']) {
                                                $purProModel->where("id", $pro['purchase_proid'])->update(array("status" => "3", "updatetime" => time()));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // var_dump($count);
                    //修改入库单状态
                    if ($count) {
                        $upStr = $this->model->where("id", $val['id'])->update(array("status" => "3", "updatetime" => time()));
                        if ($upStr) {
                            $resultCount += $upStr;
                            if ($purchase_id != "" && $purchase_id > 0) {
                                //查找采购单
                                $pusrOrder = $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->find();
                                if ($pusrOrder) {
                                    if ($pusrOrder['totalNums'] == $totalnums) {
                                        $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->update(array("status" => "3", "storage_status" => "2", "updatetime" => time()));
                                    } else {
                                        $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->update(array("storage_status" => "1", "updatetime" => time()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if ($resultCount) {
                $this->success(null, null, array("result" => "success"));
            } else {
                $this->error(__('operation failed'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取商品仓库库存列表
     */
    public function getWP() {
        if ($this->request->isAjax()) {
            $product_id = $this->request->param('id');
            $this->model = new \app\admin\model\ykjp\inventory\Wp; //设置关联表模型
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->where('product_id', 'eq', $product_id)
                    ->where("firmid", $this->auth->firmid)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->where($where)
                    ->where('product_id', 'eq', $product_id)
                    ->where("firmid", $this->auth->firmid)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();

            //循环获取仓库与分区名称
            for ($i = 0; $i < count($list); $i++) {

                $w_id = $list[$i]['warehouse_id']; //所在仓库id
                $p_id = $list[$i]['partition_id']; //所在库区id
                //获取所在仓库名称
                $warehouse = Db::name('ykjp_warehouse')
                        ->field('name')
                        ->where("firmid", $this->auth->firmid)
                        ->where('id', $w_id)
                        ->find();
                $list[$i]['name'] = $warehouse['name'];

                //获取所在库区名称
                $partition = Db::name('ykjp_partition')
                        ->field('name')
                        ->where("firmid", $this->auth->firmid)
                        ->where('id', $p_id)
                        ->find();
                $list[$i]['p_name'] = $partition['name'];
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->error(__('fail'));
    }

    /**
     * 获取商品仓库库存详情
     */
    public function getInventoryByid($ids) {
        $this->model = new \app\admin\model\ykjp\inventory\Wp;
        $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
        if (!$row) {
            $this->error(__('No Results were found'));
        } else {
            //根据仓库id和分区id获取名称
            //获取所在仓库名称
            $warehouse = Db::name('ykjp_warehouse')
                    ->field('name')
                    ->where("firmid", $this->auth->firmid)
                    ->where('id', $row['warehouse_id'])
                    ->find();
            $row['w_name'] = $warehouse['name'];

            //获取所在库区名称
            $partition = Db::name('ykjp_partition')
                    ->field('name')
                    ->where("firmid", $this->auth->firmid)
                    ->where('id', $row['partition_id'])
                    ->find();
            $row['p_name'] = $partition['name'];
            $this->success(null, null, ['row' => $row]);
        }

        $this->error(__('fail'));
    }

    /**
     * 获取仓库信息
     */
    public function getWarehouse() {
        if ($this->request->isAjax()) {
            $type = $this->request->param("type");
            if ($type) {
                $hosemModel = new \app\admin\model\ykjp\information\basisinfo\Warehouse;
                $row = $hosemModel->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            } else {
                $pid = $this->request->param("pid");
                $partModel = new \app\admin\model\ykjp\information\basisinfo\Partition;
                $row = $partModel->where("warehouse_id", $pid)->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            }
        }
        $this->error(__('fail'));
    }

    /**
     * 获取客户列表
     */
    public function getSupPro() {
        if ($this->request->isAjax()) {
            $obj = $this->request->param("obj");
            if ($obj == 1) {
                $this->model = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->field("name,contact,phone,description,id")
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->field("name,contact,phone,description,id,status")
                        ->select();
                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }

            if ($obj == 2) {
                $this->model = new \app\admin\model\ykjp\product\Product;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }
        }
        $this->error(__('Please use the correct request method'));
    }

    /**
     * 获取客户详情
     */
    public function getCustomerByid($ids) {
        $this->model = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
        $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $city = "";
            if ($row) {
                $row = $row->toArray();
                if (isset($row['city']) && $row['city'] != "") {
                    $city = explode('/', $row['city']);
                }
            }
            $this->success(null, null, ['row' => $row, "city" => $city]);
        }
        $this->error(__('No Results were found'));
    }

    /**
     * 作废销售出库单
     */
    public function abandon() {

        $ids = $this->request->post('ids'); //要作废的销售出库单ID
        $reason = $this->request->post('reason'); //作废理由
        //获取销售出库单副表相关内容
        $wp_arr = Db::name('ykjp_delivery_product')
                ->field('wp_id,nums')
                ->where('delivery_id', $ids)
                ->where('firmid', $this->auth->firmid)
                ->select();

        Db::startTrans();
        try {

            //执行作废修改
            $abandon_res = Db::name('ykjp_delivery')
                    ->where('id', $ids)
                    ->where('firmid', $this->auth->firmid)
                    ->where('status_list > 0')
                    ->update([
                'reason' => $reason,
                'status_list' => '-1',
                'updatetime' => time(),
            ]);

            //更新关联的wp表
            for ($i = 0; $i < count($wp_arr); $i++) {

                Db::name('ykjp_wp_relationship')
                        ->where('id', $wp_arr[$i]['wp_id'])
                        ->where('firmid', $this->auth->firmid)
                        ->update([
                            'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                            'freeze' => Db::raw('freeze-' . $wp_arr[$i]['nums']),
                            'updatetime' => time(),
                ]);
            }

            // 提交事务
            Db::commit();
            $this->success("提交成功", null, array("result" => "success", "url" => url("ykjp/sell/delivery/index")));
        } catch (PDOException $e) {

            Db::rollback();
            $this->error('提交失败');
        } catch (Exception $e) {

            Db::rollback();
            $this->error('提交失败');
        }
        $this->error('提交失败');
    }

    /**
     * 反审核
     */
    public function Anti($ids = null) {
        if ($ids) {
            $data = $this->model->where("firmid", $this->auth->firmid)->where("status_list", "in", [2, 3, 4, 5])->where("id", $ids)->find();
            if ($data) {

                //主表将要更新的数据
                $updateData = array("updatetime" => time(), "status_list" => "1", "reason" => null, 'cause' => null);

                //获取库存关联表需要更新的数据
                $wp_data = Db::name('ykjp_delivery_product')->field('wp_id,nums')->where('delivery_id', $ids)->select();

                // 启动事务
                Db::startTrans();
                try {

                    //更新销售出库单主表
                    Db::name('ykjp_delivery')->where('id', $ids)->update($updateData);

                    //插入副表并更新关联的wp表
                    for ($i = 0; $i < count($wp_data); $i++) {

                        //更新关联表
                        Db::name('ykjp_wp_relationship')
                                ->where('id', $wp_data[$i]['wp_id'])
                                ->where('firmid', $this->auth->firmid)
                                ->update([
                                    'inventory' => Db::raw('inventory-' . $wp_data[$i]['nums']),
                                    'freeze' => Db::raw('freeze+' . $wp_data[$i]['nums']),
                                    'updatetime' => time(),
                        ]);
                    }

                    // 提交事务
                    Db::commit();
                    $this->success("提交成功", null, array("result" => "success", "url" => url("ykjp/sell/delivery/index")));
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error('提交失败');
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error('提交失败');
                }
                $this->error('提交失败');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 确认出库
     */
    public function delivery($ids = null) {

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        if ($ids) {  //通过
            $time = time();
            $data = array("status_list" => 6, "reviewer_id" => $this->auth->id, "updatetime" => $time);
            /*
              首先修改出库单状态，然后
              通过前台传递过来的ids列表查询销售出库单的‘销售单ID’字段和《销售出库单副表》，获取销售出库单副表中的‘出库数量’、‘关联表id’和‘产品ID’字段。
              根据获取的字段:
              更新销售单表
              插入流水表
              更新关联表
              更新商品表
              更新仓库表
              更新库区表
             */

            //获取 销售出库单的‘销售单ID’字段
            $sell_id_arr = Db::name('ykjp_delivery')->field('sell_id')->where("id", "in", $ids)->where('firmid', $this->auth->firmid)->select();
            // 处理结果为列表
            for ($i = 0; $i < count($sell_id_arr); $i++) {
                if ($i == 0) {
                    $sell_id_list = $sell_id_arr[$i]['sell_id'];
                } else {
                    $sell_id_list .= ',';
                    $sell_id_list .= $sell_id_arr[$i]['sell_id'];
                }
            }

            //获取销售副表的关联表参数
            $wp_arr = Db::name('ykjp_delivery_product')
                    ->alias('d')
                    ->join('ykjp_wp_relationship w', 'd.wp_id = w.id')
                    ->field('d.nums,d.wp_id,d.product_id,w.warehouse_id,w.partition_id')
                    ->where("d.delivery_id", "in", $ids)
                    ->where('d.firmid', $this->auth->firmid)
                    ->where('w.firmid', $this->auth->firmid)
                    ->select();


            // 启动事务
            Db::startTrans();
            try {

                //一、更新销售出库单状态
                Db::name('ykjp_delivery')->where("status_list", 5)->where('firmid', $this->auth->firmid)->where("id", "in", $ids)->update($data);

                //二、更新销售单状态
                Db::name('ykjp_sell')->where("status_list", 5)->where('firmid', $this->auth->firmid)->where("id", "in", $sell_id_list)->update(['status_list' => 6, 'updatetime' => $time]);

                //三、
                for ($i = 0; $i < count($wp_arr); $i++) {

                    //插入流水表
                    Db::name('ykjp_inventory_statement')->insert([
                        'firmid' => $this->auth->firmid,
                        'product_id' => $wp_arr[$i]['product_id'],
                        'warehouse_id' => $wp_arr[$i]['warehouse_id'],
                        'partition_id' => $wp_arr[$i]['partition_id'],
                        'number' => $wp_arr[$i]['nums'],
                        'type' => '销售出库',
                        'updatetime' => $time,
                    ]);

                    //更新关联表
                    Db::name('ykjp_wp_relationship')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['wp_id'])
                            ->update([
                                'freeze' => Db::raw('freeze-' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    //更新商品表
                    Db::name('ykjp_product')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['product_id'])
                            ->update([
                                'inventory' => Db::raw('inventory-' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    //更新仓库表
                    Db::name('ykjp_warehouse')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['warehouse_id'])
                            ->update([
                                'inventory' => Db::raw('inventory-' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    // 更新库区表
                    Db::name('ykjp_partition')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['partition_id'])
                            ->update([
                                'inventory' => Db::raw('inventory-' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);
                }

                // 提交事务
                Db::commit();
                $this->success(null, null, array("result" => "成功"));
            } catch (PDOException $e) {

                Db::rollback();
                $this->error('提交失败');
            } catch (Exception $e) {

                Db::rollback();
                $this->error('提交失败');
            }

            $this->error("提交失败");
        }

        $this->error("Illegal operation");
    }

}
